package com.dai.zhenfujin.huanxin.chat;


import android.content.ClipData;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;

import com.dai.zhenfujin.R;
import com.dai.zhenfujin.addresslist.fragment.EaseChatFragment;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.db.Constant;
import com.dai.zhenfujin.huanxin.EaseChat.EaseChatNoticePresenter;
import com.dai.zhenfujin.huanxin.EaseChat.NoticeChatRow;
import com.dai.zhenfujin.message.ChatActivity;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.view.CommonDialog;
import com.dai.zhenfujin.view.CustomPopWindow;
import com.dai.zhenfujin.visitingcard.app.PersonalDetailsActivity;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.model.EaseDingMessageHelper;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.easeui.widget.presenter.EaseChatRowPresenter;
import com.hyphenate.exceptions.HyphenateException;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class ChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper {
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    public ChatActivity context;
    public CustomPopWindow customPopWindow;
    private String name;
    public static final int MESSAGE_TYPE_RECV_NOTICE = 10;
    public static final int MESSAGE_TYPE_SEND_NOTICE = 11;

    @Override
    protected void initView() {
        super.initView();
        context = (ChatActivity) getActivity();
    }

    @Override
    protected void setUpView() {
        setChatFragmentHelper(this);
        super.setUpView();
        name = SPUtils.getConversionNickName(context, toChatUsername);
        fl_alum.setVisibility(View.VISIBLE);
        tv_fabu.setText("清空");
        tv_fabu.setTextColor(getResources().getColor(R.color.yellow));
        if (!TextUtils.isEmpty(name)) {
            textTitle.setText(name);
        }
        if (name.equals("系统消息")) {
            ll_msg.setVisibility(View.GONE);
            inputMenu.setVisibility(View.GONE);
        }else {
            ll_msg.setVisibility(View.VISIBLE);
            inputMenu.setVisibility(View.VISIBLE);
        }

        // textTitle.setText("系统消息");

        fl_img.setOnClickListener(v -> context.finish());
        fl_alum.setOnClickListener(v -> {
            new CommonDialog(context, R.style.dialog, false, "确定要清空聊天记录吗?", (dialog, confirm) -> {
                if (confirm) {
                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EMConversation.EMConversationType.Chat);
                   // EMClient.getInstance().chatManager().deleteConversation(toChatUsername, true);
                    if (conversation != null) {
                        conversation.clearAllMessages();
                        messageList.refreshSelectLast();
                        isRoaming = false;
                    }
                }
                dialog.dismiss();
            }).show();
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {

    }

    /*
         设置消息扩展属性
        */
    @Override
    public void onSetMessageAttributes(EMMessage message) {


    }

    @Override
    public void onEnterToChatDetails() {

    }

    @Override
    public void onAvatarClick(String username) {
        if (!name.equals("系统消息")) {
            startActivity(new Intent(getActivity(), PersonalDetailsActivity.class)
                    .putExtra("user_id", username));
        }
    }

    @Override
    public void onAvatarLongClick(String username) {

    }

    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        return false;
    }


    /**
     * 气泡框长按事件
     *
     * @param message
     */
    @Override
    public void onMessageBubbleLongClick(EMMessage message, View view) {
        showPopowindow(message, view);
    }


    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        return false;
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return new CustomChatRowProvider();
    }




    /**
     * chat row provider  消息列表 adapter
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //here the number is the message type in EMMessage::Type
            //which is used to count the number of different chat row
            return 15;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getType() == EMMessage.Type.TXT) {

            if (message.getBooleanAttribute(NoticeChatRow.NOTICE, false)) {
                 return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_NOTICE : MESSAGE_TYPE_SEND_NOTICE;
                }
            }
            return 0;
        }

        @Override
        public EaseChatRowPresenter getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if (message.getType() == EMMessage.Type.TXT) {
                if (message.getBooleanAttribute(NoticeChatRow.NOTICE, false)) {
                    EaseChatNoticePresenter presenter = new EaseChatNoticePresenter();
                    return presenter;
                }
            }
            return null;
        }
    }

    private void showPopowindow(EMMessage message, View view) {
        int popWindowWidth = UIUtils.getDeviceDensity().widthPixels / 4;
        int popWindowHeight = UIUtils.getDeviceDensity().heightPixels / 22;
        View contentView = LayoutInflater.from(context).inflate(R.layout.popwindow_message, null);
        RelativeLayout rl_copy = contentView.findViewById(com.dai.zhenfujin.R.id.rl_copy);
        View view1 = contentView.findViewById(com.dai.zhenfujin.R.id.view1);
        RelativeLayout rl_clear = contentView.findViewById(com.dai.zhenfujin.R.id.rl_clear);
        int type = message.getType().ordinal();
        if (type == EMMessage.Type.LOCATION.ordinal() || type == EMMessage.Type.IMAGE.ordinal()) {
            rl_copy.setVisibility(View.GONE);
            view1.setVisibility(View.GONE);
        } else {
            rl_copy.setVisibility(View.VISIBLE);
            view1.setVisibility(View.VISIBLE);
        }

        rl_copy.setOnClickListener(v -> {
            clipboard.setPrimaryClip(ClipData.newPlainText(null,
                    ((EMTextMessageBody) contextMenuMessage.getBody()).getMessage()));
            customPopWindow.dissmiss();
        });

        rl_clear.setOnClickListener(v -> {
            conversation.removeMessage(contextMenuMessage.getMsgId());
            messageList.refresh();
            // To delete the ding-type message native stored acked users.
            EaseDingMessageHelper.get().delete(contextMenuMessage);
            customPopWindow.dissmiss();
        });


        customPopWindow = new CustomPopWindow.PopupWindowBuilder(context)
                .setView(contentView)
                .size(popWindowWidth, popWindowHeight)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .create();
        if (message.direct() == EMMessage.Direct.SEND) { //发
            customPopWindow.showAsDropDown(view, -UIUtils.dip2px(100), -UIUtils.dip2px(90));
        } else {
            customPopWindow.showAsDropDown(view, UIUtils.dip2px(50), -UIUtils.dip2px(90));
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
                //复制
                case ContextMenuActivity.RESULT_CODE_COPY: // copy
                    clipboard.setPrimaryClip(ClipData.newPlainText(null,
                            ((EMTextMessageBody) contextMenuMessage.getBody()).getMessage()));
                    break;
                //删除delete
                case ContextMenuActivity.RESULT_CODE_DELETE:
                    conversation.removeMessage(contextMenuMessage.getMsgId());
                    messageList.refresh();
                    // To delete the ding-type message native stored acked users.
                    EaseDingMessageHelper.get().delete(contextMenuMessage);
                    break;
                case ContextMenuActivity.RESULT_CODE_RECALL://recall  //撤回消息
                    new Thread(() -> {
                        try {
                            EMMessage msgNotification = EMMessage.createTxtSendMessage(" ", contextMenuMessage.getTo());
                            EMTextMessageBody txtBody = new EMTextMessageBody("您撤回了一条消息");
                            msgNotification.addBody(txtBody);
                            msgNotification.setMsgTime(contextMenuMessage.getMsgTime());
                            msgNotification.setLocalTime(contextMenuMessage.getMsgTime());
                            msgNotification.setAttribute(Constant.MESSAGE_TYPE_RECALL, true);
                            msgNotification.setStatus(EMMessage.Status.SUCCESS);
                            EMClient.getInstance().chatManager().recallMessage(contextMenuMessage);
                            EMClient.getInstance().chatManager().saveMessage(msgNotification);
                            messageList.refresh();
                        } catch (final HyphenateException e) {
                            e.printStackTrace();
                            UIUtils.showToastSafe(e.getMessage());
                        }
                    }).start();
                    // Delete group-ack data according to this message.
                    EaseDingMessageHelper.get().delete(contextMenuMessage);
                    break;
                default:
                    break;
            }
        }
    }
}
